<?php

class AjaxController extends Zend_Controller_Action
{

    public function init()
    {
       $mySession=new Zend_Session_Namespace();
       if(isset ($mySession->uid) && isset($mySession->username))
       {
           $this->view->username=$mySession->username;
           $this->view->uid=$mySession->uid;
       }
    }
    public function indexAction()
    {
        $this->_helper->viewRenderer->setNoRender();
    }

    public function bestsellerAction()
    {
        $this->_helper->layout()->setLayout('layout_empty');
        $request=$this->getRequest();
        $currentPage=$request->getParam('current');
        $pagesize=$request->getParam('pagesize');
        try
        {
            $currentPage=(int)$currentPage;
        }
        catch(Exception $e)
        {
            $currentPage=1;
        }

        try
        {
            $pagesize=(int)$pagesize;
        }
        catch(Exception $e)
        {
            $pagesize=3;
        }

        $book=new Admin_Model_MBook();
        // Lấy danh sách sách nổi tiếng. Tối đa là 30 cuốn
        // số sách hiển thị trên một trang của new book là 3 (<=> pagesize)
        $bestSellerTemp=$book->getBooksAdvance('bestseller', array(), array("date"=>-1), 30);
        $bestSeller=array();
         foreach($bestSellerTemp as $bookTemp)
        {
            $documentBook=$book->getBooks('book', $bookTemp["id_book"], array("_id","image","name","id_author","cost","saleoff"));
            $documentBookInterest=$book->getABook('bookinterest',array("id_book"=>$bookTemp["id_book"]), array("sumrating","view"));

            $author=new Admin_Model_MAuthor();
            $nameAuthor=$author->getAuthor($documentBook["id_author"]);

            $aBestSeller=array("_id"=>$documentBook["_id"],"image"=>$documentBook["image"],"name"=>$documentBook["name"],"author"=>$nameAuthor["name"],"id_author"=>$documentBook["id_author"],
                "cost"=>$documentBook["cost"],"saleoff"=>$documentBook["saleoff"],"sumrating"=>$documentBookInterest["sumrating"],"view"=>$documentBookInterest["view"]);

            array_push($bestSeller, $aBestSeller);
        }
        $this->view->bestSeller=$bestSeller;
        $this->view->currentPage=$currentPage;
        $this->view->pagesize=$pagesize;
    }

    public function newAction()
    {
        $this->_helper->layout()->setLayout('layout_empty');
        $request=$this->getRequest();
        $currentPage=$request->getParam('current');
        $pagesize=$request->getParam('pagesize');
        try
        {
            $currentPage=(int)$currentPage;
        }
        catch(Exception $e)
        {
            $currentPage=1;
        }

        try
        {
            $pagesize=(int)$pagesize;
        }
        catch(Exception $e)
        {
            $pagesize=9;
        }

        $book=new Admin_Model_MBook();
        // Lấy danh sách sách mới. Tối đa là 27 cuốn
        // số sách hiển thị trên một trang của new book là 9 (<=> pagesize)
        $newbookTemp=$book->getBooksAdvance('newbook', array(), array("date"=>-1), 27);
        $newbook=array();
        foreach($newbookTemp as $bookTemp)
        {
            $document=$book->getBooks('book', $bookTemp["id_book"], array("_id","image","name","id_author","cost","saleoff"));

            $author=new Admin_Model_MAuthor();
            $nameAuthor=$author->getAuthor($document["id_author"]);

            $aNewBook=array("_id"=>$document["_id"],"image"=>$document["image"],"name"=>$document["name"],"author"=>$nameAuthor["name"],"id_author"=>$document["id_author"],
                "cost"=>$document["cost"],"saleoff"=>$document["saleoff"]);

            array_push($newbook, $aNewBook);
        }
        
        $this->view->newbook=$newbook;
        $this->view->currentPage=$currentPage;
        $this->view->pagesize=$pagesize;
    }

    public function mostboughtAction()
    {
        $this->_helper->layout()->setLayout('layout_empty');
        $request=$this->getRequest();
        $currentPage=$request->getParam('current');
        $pagesize=$request->getParam('pagesize');
        try
        {
            $currentPage=(int)$currentPage;
        }
        catch(Exception $e)
        {
            $currentPage=1;
        }

        try
        {
            $pagesize=(int)$pagesize;
        }
        catch(Exception $e)
        {
            $pagesize=3;
        }

        $book=new Admin_Model_MBook();
        // Lấy danh sách sách nổi tiếng. Tối đa là 30 cuốn
        // số sách hiển thị trên một trang của new book là 3 (<=> pagesize)
        $mostBoughtTemp=$book->getBooksAdvance('mostbought', array(), array("quality"=>-1), 30);
        $mostBought=array();
         foreach($mostBoughtTemp as $bookTemp)
        {
            $documentBook=$book->getBooks('book', $bookTemp["id_book"], array("_id","image","name","id_author","cost","saleoff"));
            $documentBookInterest=$book->getABook('bookinterest',array("id_book"=>$bookTemp["id_book"]), array("sumrating","view"));

            $author=new Admin_Model_MAuthor();
            $nameAuthor=$author->getAuthor($documentBook["id_author"]);

            $aMostBought=array("_id"=>$documentBook["_id"],"image"=>$documentBook["image"],"name"=>$documentBook["name"],"author"=>$nameAuthor["name"],"id_author"=>$documentBook["id_author"],
                "cost"=>$documentBook["cost"],"saleoff"=>$documentBook["saleoff"],"sumrating"=>$documentBookInterest["sumrating"],"view"=>$documentBookInterest["view"]);

            array_push($mostBought, $aMostBought);
        }
        $this->view->mostBought=$mostBought;
        $this->view->currentPage=$currentPage;
        $this->view->pagesize=$pagesize;
    }

    public function interestAction()
    {
        $this->_helper->layout()->setLayout('layout_empty');
        $request=$this->getRequest();
        $currentPage=$request->getParam('current');
        $pagesize=$request->getParam('pagesize');
        try
        {
            $currentPage=(int)$currentPage;
        }
        catch(Exception $e)
        {
            $currentPage=1;
        }

        try
        {
            $pagesize=(int)$pagesize;
        }
        catch(Exception $e)
        {
            $pagesize=6;
        }

        $book=new Admin_Model_MBook();
        // danh sách sách được đón đọc nhiều nhất
        $bookInterestTemp=$book->getBooksAdvance('bookinterest', array(), array("totalmark"=>-1), 18);
        $bookInterest=array();
        foreach($bookInterestTemp as $bookTemp)
        {
            $document=$book->getBooks('book', $bookTemp["id_book"], array("_id","image","name","id_author","cost","saleoff"));

            $author=new Admin_Model_MAuthor();
            $nameAuthor=$author->getAuthor($document["id_author"]);

            $aBookInterest=array("_id"=>$document["_id"],"image"=>$document["image"],"name"=>$document["name"],"author"=>$nameAuthor["name"],"id_author"=>$document["id_author"],
                "cost"=>$document["cost"],"saleoff"=>$document["saleoff"],"sumrating"=>$bookTemp["sumrating"],"view"=>$bookTemp["view"]);

            array_push($bookInterest, $aBookInterest);
        }
        $this->view->bookInterest=$bookInterest;
        $this->view->currentPage=$currentPage;
        $this->view->pagesize=$pagesize;
    }
    
    public function recommendAction()
    {
        $this->_helper->layout()->setLayout('layout_empty');
        $mySession=new Zend_Session_Namespace();
        if(!isset ($mySession->uid) || !isset($mySession->username))
        {
            return;
        }
        $uid=$mySession->uid;
        $request=$this->getRequest();
        $currentPage=$request->getParam('current');
        $pagesize=$request->getParam('pagesize');
        try
        {
            $currentPage=(int)$currentPage;
        }
        catch(Exception $e)
        {
            $currentPage=1;
        }

        try
        {
            $pagesize=(int)$pagesize;
        }
        catch(Exception $e)
        {
            $pagesize=5;
        }

        $book=new Admin_Model_MBook();
        $recommend=$book->getRecommendBook($uid);
        $this->view->recommendbook=$recommend;
        $this->view->currentPage=$currentPage;
        $this->view->pagesize=$pagesize;
    }

    public function numberpagebooksameauthorAction()
    {
        $this->_helper->viewRenderer->setNoRender();
        $this->_helper->layout()->setLayout('layout_empty');
        $request=$this->getRequest();
        $idAuthor=$request->getParam('idAuthor');
        
        $book=new Admin_Model_MBook();
        $numberBookByAuthor=$book->getNumberBookByAuthor($idAuthor);
        $response=$this->getResponse();
        $response->clearAllHeaders();
        $response->clearBody();
        $response->appendBody($numberBookByAuthor);
    }

    public function bookbyauthorAction()
    {
        $this->_helper->layout()->setLayout('layout_empty');
        $request=$this->getRequest();
        $idAuthor=$request->getParam('idAuthor');

        $currentPage=$request->getParam('current');
        $pagesize=$request->getParam('pagesize');
        try
        {
            $currentPage=(int)$currentPage;
        }
        catch(Exception $e)
        {
            $currentPage=1;
        }

        try
        {
            $pagesize=(int)$pagesize;
        }
        catch(Exception $e)
        {
            $pagesize=3;
        }

        $book=new Admin_Model_MBook();
        $bookByAuthor=$book->getBookByAuthor($idAuthor);

        $this->view->currentPage=$currentPage;
        $this->view->pagesize=$pagesize;
        $this->view->bookByAuthor=$bookByAuthor;
    }

    public function checkaccountAction()
    {
        $this->_helper->viewRenderer->setNoRender();
        $this->_helper->layout()->setLayout('layout_empty');
        
        $request=$this->getRequest();
        $user=$request->getParam('user','');
        $pass=$request->getParam('pass','');
        $response=$this->getResponse();
        $response->clearAllHeaders();
        $response->clearBody();
        if($user !='' && $pass !='')
        {
            $userModel=new Personal_Model_MUser();
            if($userModel->login($user, $pass) !='')
                $response->appendBody('1');
            else
                $response->appendBody('0');
        }
        else
        {
            $response->appendBody('0');
        }
    }

    public function checkregisterAction()
    {
        $this->_helper->viewRenderer->setNoRender();
        $this->_helper->layout()->setLayout('layout_empty');

        $request=$this->getRequest();
        $user=$request->getParam('user','');
        $email=$request->getParam('email','');
        $pid=$request->getParam('pid','');

        $response=$this->getResponse();
        $response->clearAllHeaders();
        $response->clearBody();

        if($user=='' || $email=='')
        {
            $response->appendBody ('false');
            return;
        }
        
        $userModel=new Personal_Model_MUser();
        $response->appendBody($userModel->checkRegister($user, $pid, $email));
    }

    public function bookbycatAction()
    {
        $this->_helper->layout()->setLayout('layout_empty');

        $request=$this->getRequest();
        $currentPage=$request->getParam('current');
        $pagesize=$request->getParam('pagesize');
        try
        {
            $currentPage=(int)$currentPage;
        }
        catch(Exception $e)
        {
            $currentPage=1;
        }

        try
        {
            $pagesize=(int)$pagesize;
        }
        catch(Exception $e)
        {
            $pagesize=3;
        }

        $idCat=$request->getParam('idcat','');
        if($idCat=='')
            return;
        $book=new Admin_Model_MBook();
        $bookByCat=$book->getBookByCatMin($idCat);

        $this->view->currentPage=$currentPage;
        $this->view->pagesize=$pagesize;
        $this->view->bookByCat=$bookByCat;
        //echo 'tổng số sách:'.count($bookByCat);
    }

    public function newcommentAction()
    {
        $this->_helper->layout()->setLayout('layout_empty');
        $request=$this->getRequest();
        $mySession=new Zend_Session_Namespace();
        if(isset ($mySession->uid) && isset($mySession->username))
        {
            $uid=$request->getParam('uid');
            $bid=$request->getParam('bid');
            $content=$request->getParam('content');

            if($uid!=$mySession->uid)
            {
               $this->getResponse()->clearAllHeaders();
               $this->getResponse()->clearBody();
               return;
            }
            
            $book=new Admin_Model_MBook();
            $this->view->comment=$book->addCommentBook($bid, $uid, $content);
        }
    }


    // response -1 => error
    // response 2 => them lan dau vao nguoi dung public
    // response 1    => ok
    public function addcartAction()
    {
        $this->_helper->viewRenderer->setNoRender();
        $this->_helper->layout()->setLayout('layout_empty');
        $request=$this->getRequest();
        $uid=$request->getParam('uid','0');
        $bid=$request->getParam('bid');
        $number=(int)$request->getParam('number');

        $check=0;   // publi
        $mySession=new Zend_Session_Namespace();
        if($uid!='0' && $uid!=NULL)
        {
            if(isset ($mySession->uid) && isset($mySession->username))
            {
                if($uid!=$mySession->uid)
                   $check=-1;   // error
                else
                    $check=1;   // user login
            }
        }

        if($check==-1)
        {
            echo '-1';
            return;
        }

        $cartModel=new Personal_Model_MCart();
        $idCart='';
        if($check==0)   // public cart
        {
            if(isset($mySession->idcart))
            {
                $idCart= $mySession->idcart;
            }
        }
        $result= $cartModel->addCart($bid, $uid, $number,$idCart);
        //echo $result;
        if($result!=FALSE && !is_int($result) )  // them thanh cong
        {
            if(!isset($mySession->idcart))
            {
                $mySession->idcart=$result;
                $mySession->setExpirationSeconds(3600, 'idcart');
				
				if($check==0)
				{
					echo '2';
					return;
				}
            }
            echo '1';
            return;
        }
        else if($result==FALSE)
        {
            echo '-1';
            return;
        }
        
    }

    // lấy thông tin cá nhân của user
    // là thông tin của người được tặng sách
    public function getuserinfoAction()
    {
        $this->_helper->viewRenderer->setNoRender();
        $this->_helper->layout()->setLayout('layout_empty');
        $request=$this->getRequest();
        $uid=$request->getParam('uid','0');
        if($uid=='0')
            return;
        $userModel=new Personal_Model_MUser();
        $user=$userModel->getPersonalInfo($uid);
        if(count($user)==0)
            return;
        $this->getResponse()->appendBody(json_encode($user));
    }
}

